package edu.whut.mall.common.exception;

import edu.whut.mall.common.api.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * @program: d9lab-mall
 * @description: 全局异常处理
 * @author: Wayne
 * @create: 2020-04-11 10:52
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义通用异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MallException.class)
    public CommonResult handle(MallException e) {
        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }
    /**
     * 统一处理请求参数校验(实体对象传参-form)
     *
     * @param e BindException
     * @return CommonResult
     */
    @ExceptionHandler(BindException.class)
    public CommonResult validExceptionHandler(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return CommonResult.validateFailed(message.toString());
    }

    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return CommonResult
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public CommonResult handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return CommonResult.validateFailed(message.toString());
    }

    /**
     * 统一处理请求参数校验(json)
     *
     * @param e MethodArgumentNotValidException
     * @return CommonResult
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return CommonResult.validateFailed(message.toString());
    }

    @ExceptionHandler(value = UnauthorizedException.class)
    public CommonResult handleUnauthorizedException(UnauthorizedException e) {
        return CommonResult.failed("沒有登陸");
    }

    @ExceptionHandler(value = AuthenticationException.class)
    public CommonResult handleAuthenticationException(AuthenticationException e) {
        return CommonResult.failed("暂时没有权限");
    }

    @ExceptionHandler(value = AuthorizationException.class)
    public CommonResult handleAuthorizationException(AuthorizationException e){
        return CommonResult.failed("暂时没有权限");
    }


}
